package com.wanglin.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.wanglin.reggie.common.BaseContext;
import com.wanglin.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LoginCheckFilter
 *
 * @author 王林
 * @version 1.0
 * @description 登录检查过滤器
 * @date 2025/5/27 18:55
 * @projectName reggie_take_out
 * @package com.wanglin.reggie.filter
 * @className com.wanglin.reggie.filter.LoginCheckFilter
 * @copyright Copyright 2020 Theofanis, Wang Lin All rights reserved.
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 定义AntPathMatcher对象，用于匹配URL
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将ServletRequest和ServletResponse转换为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);
        // 定义不需要检查的URL
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };
        // 检查URL是否在不需要检查的URL中
        boolean check = check(urls, requestURI);
        if (check) {
            log.info("不需要检查的请求：{}", requestURI);
            // 如果在，则直接放行
            filterChain.doFilter(request, response);
            return;
        }
        // 检查用户是否已经登录
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，用户ID为：{}", request.getSession().getAttribute("employee"));
            // 从session中获取employee的id
            Long empId = (Long) request.getSession().getAttribute("employee");
            // 将employee的id设置到BaseContext中
            BaseContext.setCurrentId(empId);
            // 如果已经登录，则放行
            filterChain.doFilter(request, response);
            return;
        }
        log.info("用户未登录");
        // 如果没有登录，则返回错误信息
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    // 检查URL是否在不需要检查的URL中
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            // 使用AntPathMatcher对象匹配URL
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
